﻿namespace CookieTerm
{
    using System;
    using System.Globalization;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    public struct XmlColor : IXmlSerializable
    {
        public byte R;
        public byte G;
        public byte B;

        public static XmlColor FromRgb(int rgb)
        {
            return new XmlColor
            {
                R = (byte)((0x00FF0000 & rgb) >> 16),
                G = (byte)((0x0000FF00 & rgb) >> 8),
                B = (byte)(0x000000FF & rgb)
            };
        }

        public int ToRgb()
        {
            return this.R << 16 | this.G << 8 | this.B;
        }

        #region IXmlSerializable Members
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            writer.WriteString(ToRgb().ToString(CultureInfo.InvariantCulture));
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            reader.ReadStartElement();
            try
            {
                this = FromRgb(Convert.ToInt32(reader.ReadString(),CultureInfo.InvariantCulture));
            }
            catch
            {
                this.R = 0;
                this.G = 0;
                this.B = 0;
            }
            reader.ReadEndElement();
        }
        #endregion
    }
}